﻿using System.Linq;

using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions.Helpers;

using NHibernate;
using NHibernate.ByteCode.Castle;
using NHibernate.Linq;
using NHibernate.Tool.hbm2ddl;

namespace TheKitchen.Querying.Core.DataAccess
{
    public class QueryContext : NHibernateContext
    {
        private static readonly FluentConfiguration configuration;
        private static readonly ISessionFactory sessionFactory;

        static QueryContext()
        {
            configuration = Fluently
                .Configure()
                .Database(MsSqlConfiguration.MsSql2008
                    .ConnectionString(x => x.FromConnectionStringWithKey("QueryContext"))
                    .ProxyFactoryFactory(typeof (ProxyFactoryFactory).AssemblyQualifiedName))
                .Mappings(m => m.AutoMappings.Add(AutoMap
                    .AssemblyOf<QueryContext>()
                    .Where(x => typeof (Entity).IsAssignableFrom(x))
                    .UseOverridesFromAssemblyOf<QueryContext>()
                    .Conventions.Add(
                        ForeignKey.EndsWith("Id"),
                        Table.Is(x => Inflector.Pluralize(x.EntityType.Name)))));

            sessionFactory = configuration.BuildSessionFactory();
        }

        public IQueryable<Recipe> Recipes
        {
            get { return Session.Linq<Recipe>(); }
        }

        protected override ISession ProvideSession()
        {
            return sessionFactory.OpenSession();
        }

        public static void CreateDatabase()
        {
            new SchemaExport(configuration.BuildConfiguration()).SetOutputFile("CreateScriptQueryContext.sql").Execute(true, true, false);
        }

        internal void Add(Recipe recipe)
        {
            Session.Save(recipe);
        }
    }
}